package app.fugema.shop.main.login.vm;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.base.common.app.BaseConstant;
import com.base.common.app.LoginUtils;
import com.base.common.model.http.jackSon.JacksonUtils;
import com.base.common.netBeanPackage.BaseApiResult;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.LogUtil;
import com.base.common.utils.UIUtils;
import com.base.common.viewmodel.BaseViewModel;
import com.base.common.viewmodel.NetWorkFunction;
import com.jeremyliao.liveeventbus.LiveEventBus;
import app.fugema.shop.constants.PublicGlobal;
import app.fugema.shop.http.HttpService;
import app.fugema.shop.main.login.model.AlipayAuthResult;
import app.fugema.shop.main.login.model.AlipayUserResult;
import app.fugema.shop.main.login.model.CheckImgResult;
import app.fugema.shop.main.login.model.CheckVerCodeResult;
import app.fugema.shop.main.login.model.MLoginBean;
import app.fugema.shop.main.login.model.MUserInfo;
import app.fugema.shop.main.login.model.OauthInfoBean;
import app.fugema.shop.main.login.model.RegisterResult;

import java.util.HashMap;
import java.util.Map;

import app.fugema.shop.main.setting.model.ContactResult;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;

public class LoginVM extends BaseViewModel {
    public LoginVM(@NonNull Application application) {
        super(application);
    }


    /**
     *  获取 绑定手机号的 验证码
     * @param phoneNum
     * @param userKey
     * @return
     */
    public MutableLiveData<LiveDataWrapper<BaseApiResult>> getBindTelVerfyCode(String phoneNum , String userKey,String imgCode,String imgId)
    {
        //处理手机号
        String tel = phoneNum.replaceAll(" ", "");

        Map<String,Object> phoneParam = new HashMap<>();
        //contact手机号码或邮箱 String userkey 用户凭证  Bool checkBind  是否检测绑定状态
        phoneParam.put("contact",tel);
        phoneParam.put("userkey",userKey);
        phoneParam.put("checkBind",true);
        phoneParam.put("imageCheckCode",imgCode);
        phoneParam.put("id",imgId);
        return send(HttpService.getHttpServer().getBindTelVerfyCode(phoneParam));
    }

    /**
     * 验证 绑定手机的验证码
     * @param mobile
     * @param code
     * @param userkey
     * @return
     */
    public MutableLiveData<LiveDataWrapper<BaseApiResult>> checkBindTelVerfyCode(String mobile,String code,String userkey)
    {
        Map<String, Object> map = new HashMap<>();
        //手机号码或邮箱
        map.put("contact", mobile.replaceAll(" ", ""));
        map.put("checkCode", code);
        map.put("userkey", userkey);
        return send(HttpService.getHttpServer().checkBindTelVerfyCode(map));
    }


    /**
     *  获取 图片 验证码
     * @return
     */
    public MutableLiveData<LiveDataWrapper<CheckImgResult>> getImgCheckCode()
    {
        return send(HttpService.getHttpServer().getImgCheckCode());
    }

    /**
     *  用户注册
     * @param userName
     * @param pwd
     * @return
     */
    public MutableLiveData<LiveDataWrapper<RegisterResult>> registerUser(String userName, String pwd,String verCode)
    {
        Map<String, Object> map = new HashMap<>();
        //mobile.replaceAll(" ", "")
        // 2种方式 选一 不能 同时为空
        // 注册方式一   用户名 密码 注册
        //userName  用户名
        map.put("userName",userName);
        map.put("password",pwd);
        /*
        oauthtype weixin
        oauthopenId oN8gr6MUyBR5b0OP4MCl3JzWavNc
        unionid oQ7Pu55KP8_N6raqxeZ2ziJPd7l0
        headimgurl https://thirdwx.qlogo.cn/mmopen/vi_32/PiajxSqBRaEIeDgXN0nosJNChmpVxwOaY35UZmmBywB9Kia8MUzVuZfxh1jJz31bSJvylfkSUibibWaZMayMcPUGBA/132
        oauthnickname 梦
        sex 1
        province 南
        city 阳
        oauthtype qq
        oauthopenId 16C0C54D2E4DC772A8D224942BB106E9
        headimgurl http://thirdqq.qlogo.cn/qqapp/1108724047/16C0C54D2E4DC772A8D224942BB106E9/100
        oauthnickname 有梦
        province 河͗
        city ͗阳
        */
        /*
        // 注册方式二   第三方登录注册   微信 QQ
        //oauthType   类型
        map.put("oauthType","oauthType");
        map.put("email","email");
        //OpenId
        map.put("oauthOpenId","OpenId");
        //昵称
        map.put("oauthNickName","oauthNickName");
        */

        //验证码
        map.put("code",verCode);
        ////{"success":true,"UserId":"691","CouponNum":0}
        return send(HttpService.getHttpServer().registerUser(map));
    }


    /**
     *  账号密码 登陆
     * @param userName
     * @param password
     * @return
     */
    public MutableLiveData<LiveDataWrapper<MUserInfo>> login(String userName, String password)
    {
        return send(HttpService.getHttpServer().login(userName,password)
                .flatMap(new NetWorkFunction<MLoginBean, ObservableSource<MUserInfo>>() {
                    @Override
                    public ObservableSource<MUserInfo> onSuccess(MLoginBean loginInfo)
                    {
                        LogUtil.e("LoginVM:login-> flatMap()->onSuccess =  " +" UserKey = "+ loginInfo.getUserKey() +" UserI = " + loginInfo.getUserId() );
                        return userInfo(loginInfo.getUserKey(),loginInfo.getUserId());
                    }

                    @Override
                    public boolean isEmptyData(MLoginBean data) {
                        return UIUtils.isEmpty(data);
                    }

                    @Override
                    public ObservableSource<MUserInfo> onFailure(MLoginBean loginInfo)
                    {
                        //{"success":false,"msg":"用户名或密码错误","code":103}
                        MUserInfo failure =  new MUserInfo();
                        failure.setSuccess( true );
                        failure.setMsg( loginInfo.getMsg() );
                        failure.setCode( loginInfo.getCode() );
                        return getFailureObservable(failure);
                    }
                }));
    }


    /**
     * 第三方登录 注册
     * @param
     * @return
     */
    public MutableLiveData<LiveDataWrapper<MUserInfo>> registerUserByUmeng( OauthInfoBean mAuthInfo )
    {
        Map<String, Object> map = new HashMap<>();
        //mobile.replaceAll(" ", "")
        // 2种方式 选一 不能 同时为空
        // 注册方式一   用户名 密码 注册
        //userName  用户名
        //map.put("userName",userName);
        //map.put("password",pwd);
        /*
        oauthtype weixin
        oauthopenId oN8gr6MUyBR5b0OP4MCl3JzWavNc
        unionid oQ7Pu55KP8_N6raqxeZ2ziJPd7l0
        headimgurl https://thirdwx.qlogo.cn/mmopen/vi_32/PiajxSqBRaEIeDgXN0nosJNChmpVxwOaY35UZmmBywB9Kia8MUzVuZfxh1jJz31bSJvylfkSUibibWaZMayMcPUGBA/132
        oauthnickname 梦
        sex 1
        province 南
        city 阳
        oauthtype qq
        oauthopenId 16C0C54D2E4DC772A8D224942BB106E9
        headimgurl http://thirdqq.qlogo.cn/qqapp/1108724047/16C0C54D2E4DC772A8D224942BB106E9/100
        oauthnickname 有梦
        province 河͗
        city ͗阳
        */
        //String oauthType, String oauthopenId,String unionid,String headimgurl ,String oauthnickname,int sex,String province,String city
        // 注册方式二   第三方登录注册   微信 QQ 支付宝
        //oauthType   类型
        map.put("oauthType",mAuthInfo.getOauthType());
        //OpenId
        map.put("oauthopenId",mAuthInfo.getOauthopenId());
        //昵称
        map.put("oauthnickname",mAuthInfo.getOauthnickname());
        if( UIUtils.isNotEmpty(mAuthInfo.getHeadimgurl()))
        {
            map.put("headimgurl",mAuthInfo.getHeadimgurl());
        }
        //变化字段
        if( UIUtils.isNotEmpty(mAuthInfo.getUnionid()) )
        {
            map.put("unionid",mAuthInfo.getUnionid());
        }
        map.put("sex",mAuthInfo.getSex());
        if( UIUtils.isNotEmpty( mAuthInfo.getProvince() ) )
        {
            map.put("province",mAuthInfo.getProvince());
        }
        if(UIUtils.isNotEmpty( mAuthInfo.getCity() ))
        {
            map.put("city",mAuthInfo.getCity());
        }
        ////{"success":true,"UserId":"691","CouponNum":0}
        LogUtil.e("第三方授权登录", JacksonUtils.transBean2Json(map));
        //HttpService.getHttpServer().registerUser(map)

        return send( HttpService.getHttpServer().appLogin(map)
                     .flatMap(new NetWorkFunction<MLoginBean, ObservableSource<MUserInfo>>()
                     {
                        @Override
                        public ObservableSource<MUserInfo> onSuccess(MLoginBean loginInfo)
                        {
                            LogUtil.e("LoginVM:login-> flatMap()->onSuccess =  " +" UserKey = "+ loginInfo.getUserKey() +" UserI = " + loginInfo.getUserId() );
                            return userInfo(loginInfo.getUserKey(),loginInfo.getUserId());
                        }

                        @Override
                        public boolean isEmptyData(MLoginBean data) {
                            return UIUtils.isEmpty(data);
                        }

                        @Override
                        public ObservableSource<MUserInfo> onFailure(MLoginBean loginInfo)
                        {
                            //{"success":false,"msg":"未绑定账户","code":104}
                            MUserInfo failureInfo = new MUserInfo();
                            failureInfo.setSuccess(true);
                            failureInfo.setMsg( loginInfo.getMsg() );
                            failureInfo.setCode( loginInfo.getCode() );
                            return getFailureObservable(failureInfo);
                        }
                    }));
    }

    /**
     *  第三方登录  拿到openId后注册 完成 在根据信息 获取 MLoginBean
     * @param params
     * @return
     */
    public  Observable<MLoginBean>  appLogin(Map<String,Object> params)
    {
           return HttpService.getHttpServer().appLogin(params);
    }

    /**
     * 获取用户信息
     *
     * @param userKey
     * @return
     */
    public Observable<MUserInfo> userInfo(String userKey , String userId)
    {
        //保存token
        LoginUtils.saveToken(userKey, Integer.parseInt(userId));

        return HttpService.getHttpServer().userInfo(userKey)
                .map(new NetWorkFunction<MUserInfo, MUserInfo>() {
                    @Override
                    public MUserInfo onSuccess(MUserInfo userInfo)
                    {
                        //保存登录信息
                        PublicGlobal.setUserInfo(userInfo);
                        //发送用户信息刷新事件
                        LiveEventBus.get(BaseConstant.EventKey.USER_UPDATE_SUCCESS, MUserInfo.class).post(userInfo);
                        return userInfo;
                    }

                    @Override
                    public MUserInfo onFailure(MUserInfo userInfo)
                    {
                        return userInfo;
                    }
                });

    }


    public String checkedCode(String code) {
        int len = code.length();
        if (len == 0) {
            return "验证码不可为空";
        }
        return null;
    }

    public String checkedPassword(String password) {
        int len = password.length();
        if (len == 0) {
            return "密码不可为空";
        } else if (len < 4) {
            return "密码不可少于4位";
        }
        return null;
    }


    /**
     *   验证  (重置密码) 手机收到的验证码
     * @param contact
     * @param imgCode
     * @return
     */
    public MutableLiveData<LiveDataWrapper<CheckVerCodeResult>> checkPhoneVerifyCode(String contact, String imgCode)
    {
        //手机号码或邮箱
        return send(HttpService.getHttpServer().checkPwdVerifyCode(contact, imgCode));
    }


    /**
     * (发送图片验证码获取手机邮箱验证码)
     * @param id
     * @param contact
     * @param imgCode
     * @return
     */
    public MutableLiveData<LiveDataWrapper<BaseApiResult>> sendVerifyCode(String id, String contact, String imgCode)
    {
        //绑定过的手机号码或邮箱
        return send(HttpService.getHttpServer().getPwdVerifyCode(id,contact, imgCode));
    }


    /**
     *  修改密码
     * @param cert
     * @param pwd
     * @return
     */
    public MutableLiveData<LiveDataWrapper<BaseApiResult>> postChangePwd(String cert, String pwd)
    {
        return send(HttpService.getHttpServer().changePwd(cert, pwd));
    }

    /**
     *  修改支付密码
     * @param cert
     * @param pwd
     * @return
     */
    public MutableLiveData<LiveDataWrapper<BaseApiResult>> postChangePayPwd(String cert, String pwd)
    {
        return send(HttpService.getHttpServer().changePayPwd(cert, pwd));
    }

    /**
     *  查询用户绑定的 手机
     * @param userKey
     * @return
     */
    public MutableLiveData<LiveDataWrapper<ContactResult>> getUserBindPhone(String userKey)
    {
        return send(HttpService.getHttpServer().getUserBindPhone(userKey));
    }

    /**
     *  支付宝登录  获取支付宝用户信息
     * @return
     */
    public MutableLiveData<LiveDataWrapper<AlipayAuthResult>> getAlipayUser()
    {
        return send(HttpService.getHttpServer().getAlipayUser());
    }

    /**
     * 获取支付宝用户信息
     * @param authCode
     * @return
     */
    public MutableLiveData<LiveDataWrapper<AlipayUserResult>> getAlipayUserByAuth(String authCode)
    {
        return send(HttpService.getHttpServer().getAlipayUserByAuth(authCode ));
    }


}
